# /etc/profile



import subprocess, time, logging

screens = []


def os_run(command):
	call = subprocess.run(
		command.split(" "), 
		stdout = subprocess.PIPE,
		text = True
		)

	return call.stdout

def init_screen():
	out = os_run("xrandr -q")
	lines = out.split("\n")
	for line in lines:
		if " connected " in line:
			if " primary " not in line:
				side_screen = line.split(" ")[0]
				rotate_screen(side_screen)
				logging.warning(f"init rotate screen:{side_screen}")


def check_new_screen():
	global screens
	out = os_run("xrandr -q")
	lines = out.split("\n")
	current_screen = []
	for line in lines:
		if " connected " in line:
			current_screen.append(line.split(" ")[0])
	logging.warning(f"current_screen:{current_screen}")
	if len(screens) == 0:
		screens = current_screen
		logging.warning(f"initialed screen: {screens}")
		if len(current_screen)>1:
			init_screen()
		return
	if screens != current_screen:
		for ins in current_screen:
			if ins not in screens:
				screens.append(ins)
				return ins
	return False

def rotate_screen(screen_name):
	os_run(f"xrandr --output {screen_name} --rotate right")


if __name__=='__main__':
	while True:
		new_screen = check_new_screen()
		if new_screen:
			time.sleep(10)
			rotate_screen(new_screen)
			logging.warning(new_screen)
		time.sleep(1)
		logging.warning("IDLE")
